#include <retro.h>
#include "player.h"
#include "player.spritemap.h"
#include "player.frame.h"

using namespace Retro::Player;
using namespace Retro::Player::Graphic;

SpriteMap::SpriteMap()
{
  mMap    = NULL;
  mNodes  = NULL;
}

VOID SpriteMap::setMap(const Data::SpriteMap* iValue)
{
  if (mMap)
  {
    Display::FreeSpriteNodes(mNodes, mMap->getLayers());
  }

  if (mMap = iValue)
  {
    mNodes = new Display::SpriteNode*[mMap->getLayers()];
    memset(mNodes, 0, sizeof(mNodes[0]) * mMap->getLayers());

    Display::GetSpriteNodes(mMap, mNodes);
  }
  else
  {
    mNodes = NULL;
  }
}

VOID SpriteMap::init(Display::DisplayDevice* iDevice)
{
  Display::InitializeSpriteNodes(
    iDevice,
    mNodes,
    mMap->getLayers(),
    &Frame::get()->getProject());
}

VOID SpriteMap::uninit(Display::DisplayDevice* iDevice)
{
}

VOID SpriteMap::render(
  Display::DisplayDevice* iDevice,
  INT iX,
  INT iY
  ) const
{
  if (!mMap) return;

  for (INT i = 0; i < mMap->getLayers(); ++i)
  {
    Display::SpriteNode* wNode = mNodes[i];

    while (wNode)
    {
      Display::DrawSpriteNode(
        iDevice,
        wNode,
        wNode->viewBounds,
        Geom::Point::get(iX, iY));

      wNode = wNode->next;
    }
  }
}
